package com.lagou.edu.service.impl;

import com.lagou.edu.client.EmailServiceFeignClient;
import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.CodeService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;
    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public boolean create(String email) {
        try {
            SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 6);
            // 设置字体
            specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
            // 设置类型，纯数字、纯字母、字母数字混合
            specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
            String code = specCaptcha.text().toLowerCase();

            // 保存验证码
            AuthCode authCode = new AuthCode();
            authCode.setCode(code);
            authCode.setEmail(email);
            authCode.setCreatetime(LocalDateTime.now());
            authCode.setExpiretime(LocalDateTime.now().plusMinutes(10));
            authCodeDao.save(authCode);

            //发送邮件
            emailServiceFeignClient.send(email, "yanzemaceshi", code);
            return true;
        } catch (Exception ex){
            return false;
        }
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = authCodeDao.findByEmailAndExpiretimeAfter(email, LocalDateTime.now());
        if (Objects.isNull(authCode)) {    //验证码过期
            return 2;
        } else if (!authCode.getCode().equals(code)) {   //验证码错误
            return 1;
        }
        return 0;   //验证码正确
    }

}